
module audio_wrapper
(
   input                       reset,
   input                       reg_clk,
   if_reg_ctrl.slave           reg_if,
   
   input                       clk_3p072m,
   output                      iis_sclk,
   output                      iis_lrck,
   output                      iis_data
);
   
   reg  [31:0]                 test_reg;
   wire [31:0]                 bclk_clk_rpt;
   
   reg                         audio_wdata_we;
   reg  [31:0]                 audio_wdata;
   wire [10:0]                 audio_fifo_wlvl;
   wire [10:0]                 audio_fifo_rlvl;
   wire [31:0]                 audio_rdata;
   reg  [5:0]                  audio_req;
   
   // Reg
   always @(posedge reg_clk)
   begin
      if(reset)
      begin
         test_reg <= 32'h12345678;
      end
      else if(&reg_if.we && reg_if.en)
      begin
         case(reg_if.addr)
            8'h00 : test_reg <= reg_if.wdata[31:0];
            8'h10 :
            begin
               audio_wdata_we <= 1'b1;
               audio_wdata <= reg_if.wdata[31:0];
            end
         endcase
      end
      else if(reg_if.en)
      begin
         case(reg_if.addr)
            8'h00 : reg_if.rdata = test_reg;
            8'h01 : reg_if.rdata = bclk_clk_rpt;
            8'h10 : reg_if.rdata = audio_wdata;
            8'h11 : reg_if.rdata = audio_fifo_wlvl;
            default : reg_if.rdata = 32'hdeadbeef;
         endcase
      end
      else
      begin
         audio_wdata_we <= 1'b0;
      end
   end
   
   // Audio buffer
   fifo
   #(
      .DWID                    ( 32 ),
      .AWID                    ( 11 )
   )
   u_audio_fifo
   (
      .wclk                    ( reg_clk ),
      .we                      ( audio_wdata_we ),
      .wdata                   ( audio_wdata ),
      .wlevel                  ( audio_fifo_wlvl ),
      .rclk                    ( clk_3p072m ),
      .re                      ( &audio_req && |audio_fifo_rlvl ),
      .rdata                   ( audio_rdata ),
      .rlevel                  ( audio_fifo_rlvl )
   );
   
   always @(posedge clk_3p072m)
   begin
      audio_req <= audio_req + 1;
   end
   
   // Audio to I2S
   audio2iis
   (
      .clk_3p072m              ( clk_3p072m ),
      .audio_data_valid        ( &audio_req && |audio_fifo_rlvl ),
      .audio_data              ( audio_rdata ),
      .iis_sclk                ( iis_sclk ),
      .iis_lrck                ( iis_lrck ),
      .iis_data                ( iis_data )
   );
   
   // Audio clock test
   clock_meter
   #(
      .TIME_1S                 ( 100_000_000 )
   )
   u_clock_meter
   (
      .clk_ref                 ( reg_clk ),
      .clk_tst                 ( clk_3p072m ),
      .clk_rpt                 ( bclk_clk_rpt )
   );
   
endmodule